<?php
namespace app\admin\controller;

use app\admin\model\AuthGroup as AuthGroupModel;
use app\admin\model\User as UserModel;
use Db;
use Request;

//use Db;
/**
 * 用户分信息
 */
class User extends Base
{
    /*
    显示分类信息列表
     */
    public function index($search = '', $val = '')
    {
        $where = '';

        $search = !empty($search) ? trim($search) : '';
        $val    = !empty($val) ? trim($val) : '';

        // if (Request::has('user')) {
        //     $where[] = ['user_name', 'like', '%' . Request::param('user/s', '', 'strip_tags') . '%'];
        // } else if (Request::has('nickname')) {
        //     $where[] = ['nickname', 'like', '%' . Request::param('nickname/s', '', 'strip_tags') . '%'];
        // } else if (Request::has('email')) {
        //     $where[] = ['email', 'like', '%' . Request::param('email/s', '', 'strip_tags') . '%'];
        // }

        // $field = 'a.*,GROUP_CONCAT(b.group_id) as grid,GROUP_CONCAT(c.title) as authtitle';
        // $list  = UserModel::alias('a')->field($field)
        //     ->join('auth_group_access b', 'b.uid = a.id', 'LEFT')
        //     ->join('auth_group c', 'c.id = b.group_id', 'LEFT')
        //     ->group('b.uid')
        //     ->where('a.tid', 1)
        //     ->where($where)
        //     ->order('a.id ASC')
        //     ->paginate(config('webconfig.page'),false,['query'=>Request::param()]);

        // if (!empty(Request::param())) {
        //     //取得搜索值
        //     $search    = array_keys(Request::param())[0];
        //     $searchval = current(Request::param());
        // }

        $this->assign([
            'search' => $search,
            'val'    => $val,
        ]);
        return $this->fetch();
    }

    public function ajaxlist($search = '', $val = '', $page = 1, $limit = '')
    {
        $where  = '';
        $search = !empty($search) ? trim($search) : '';
        $val    = !empty($val) ? trim($val) : '';

        if ($search == 'user' && $val) {
            //$userid  = \Db::name('user')->where([['user_name', '=', $val]])->value('id');
            $where[] = ['user_name', 'like', '%' . $val . '%'];
        } else if ($search == 'nickname' && $val) {
            $where[] = ['nickname', 'like', '%' . $val . '%'];
        } else if ($search == 'nickname' && $val) {
            $where[] = ['email', 'like', '%' . $val . '%'];
        }

        $page = !empty($page) ? $page : 1;

        $field = 'a.*,GROUP_CONCAT(b.group_id) as grid,GROUP_CONCAT(c.title) as authtitle';
        $list  = UserModel::alias('a')->field($field)
            ->join('auth_group_access b', 'b.uid = a.id', 'LEFT')
            ->join('auth_group c', 'c.id = b.group_id', 'LEFT')
            ->group('b.uid')
            ->where('a.tid', 1)
            ->where($where)
            ->order('a.id ASC')
            ->page($page, $limit)->select();
        $count = UserModel::where($where)->where('tid', 1)->count();
        foreach ($list as $k => $v) {
            $list[$k]['sex'] = $v['sex'] == 1 ? '男' : '女';
        }
        $list = ["code" => 0, "msg" => "加载中", "count" => $count, "data" => $list];
        return json($list);
    }

    /*
    信息添加
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $post = $this->request->post();

            $result = $this->validate($post, 'app\admin\validate\User.add');
            if (true !== $result) {
                return $this->error($result);
            }

            $data = UserModel::create($post);

            if (isset($post['role']) && isset($data->id)) {
                addlog($data->id, $data->user_name);
                //添加后再给权限，id
                $astauts = $this->editauth($post['role'], $data->id);
                if (false === $astauts) {
                    //权限
                    return $this->error('权限失败');
                }
            }

            if (!empty($data)) {
                return $this->success('添加成功', 'admin/User/index');
            }
        }
        $data = AuthGroupModel::where(['status' => 1])->select();
        $this->assign('tname', $data);
        return $this->fetch();
    }

    /*
    信息编辑
     */
    public function edit()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        //$id = Request::has('id') ? Request::param('id', 0, 'intval') : 0;
        if ($this->request->isPost()) {

            $post = $this->request->post();

            $result = $this->validate($post, 'app\admin\validate\User.edit');
            if (true !== $result) {
                return $this->error($result);
            }

            $post['role'] = isset($post['role']) ? $post['role'] : ''; //由于layui 无选择时不会传值所以定义一个无选择状态
            //if (isset($post['role'])) {
            $astauts = $this->editauth($post['role'], $id);
            if (false === $astauts) {
                //权限
                return $this->error('权限失败');
            }
            //}
            //$model = new UserModel;
            $model = UserModel::edit($post, $id);
            //echo $model;
            if ($model || $astauts) {
                //addlog($id, $post['user_name']);
                return $this->success('修改成功', 'admin/User/index');
            } else {
                return $this->error('修改失败');
            }
        }

        $info = UserModel::get($id);
        if (empty($info)) {return $this->error('id参数错误');}

        $data  = AuthGroupModel::where(['status' => 1])->select();
        $ninfo = Db::name('auth_group_access')->where('uid', $id)->select(); //当前拥有的

        foreach ($data as $k => $v) {
            foreach ($ninfo as $k2 => $v2) {
                if ($v['id'] == $v2['group_id']) {
                    $data[$k]['checked'] = 'y';
                }
            }
        }
        $this->assign([
            'tname' => $data,
            'info'  => $info,
        ]);
        return $this->fetch();
    }

    public function auth()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($this->request->isPost()) {

            $post         = $this->request->post();
            $post['role'] = isset($post['role']) ? $post['role'] : ''; //由于layui 无选择时不会传值所以定义一个无选择状态
            //if (isset($post['role'])) {
            if (false === $this->editauth($post['role'], $id)) {
                //权限
                return $this->error('权限失败');
            } else {
                //addlog($id, $post['role']);
                return $this->success('权限成功', 'admin/User/index', '', 1);
            }
            //}
        }

        $data = AuthGroupModel::where(['status' => 1])->select(); //所有权限
        $info = Db::name('auth_group_access')->where('uid', $id)->select(); //当前拥有的
        $user = Db::name('user')->where('id', $id)->find(); //当前拥有的
        foreach ($data as $k => $v) {
            foreach ($info as $k2 => $v2) {
                if ($v['id'] == $v2['group_id']) {
                    $data[$k]['checked'] = 'y';
                }
            }
        }
        $this->assign([
            'user'  => $user,
            'tname' => $data,
        ]);
        return $this->fetch();
    }

    /*
    信息删去
     */
    public function delete($value = '')
    {
        $id     = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $data   = UserModel::get($id); // 获取要删除的对象  不存在时返回 null    $user::destroy($id) //批量删时尽量用，返回记录条数，没有删除返回0
        $strlog = $data->user_name;
        if (!empty($data)) {
            if ($data->delete()) {
                addlog($id, $strlog);
                return $this->success('删去成功', 'admin/User/index', '', 1);
            }
        }
        return $this->error('删去失败');
    }

    /**
     * 指定权限
     * @param  array $arr 指定权限值
     * @param  INT $id  用户ID
     * @return [type]      [description]
     */
    private function editauth($arr, $id)
    {

        if (isset($arr) && is_array($arr)) {
            $addList = array();
            foreach ($arr as $k => $v) {
                $addList[] = ['uid' => $id, 'group_id' => $v];
            }
            $data  = Db::name('auth_group_access')->where('uid', $id)->delete();
            $data1 = Db::name('auth_group_access')->insertAll($addList);
        } else {
            $data = Db::name('auth_group_access')->where('uid', $id)->delete();
        }
        return true;
    }

    /**
     * 快捷操作
     * @return [type] [description]
     */
    public function quickedit()
    {
        //$id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if (Request::isPost()) {
            if (Request::has('remark')) {
                $data   = ['id' => Request::post('id/d'), 'remark' => Request::post('remark')]; //备注
                $strlog = "备注remark值：" . Request::post('remark');
            } else if (Request::has('status')) {
                $data   = ['id' => Request::post('id/d'), 'status' => Request::post('status')]; //状态
                $strlog = "状态status值：" . Request::post('status');
            }
            $model = UserModel::update($data);
            //print_r($model);
            if (!empty($model)) {
                addlog(Request::post('id/d'), $strlog);
                return $this->success('修改成功');
            } else {
                return $this->error('修改失败');
            }
        }
    }

}
